package com.riwon.im.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.riwon.im.common.constant.UserConstant;
import com.riwon.im.dao.UserMapper;
import com.riwon.im.pojo.Msg;
import com.riwon.im.pojo.User;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wpy
 * @since 2018-05-09
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Resource
    private IMsgService msgServiceImpl;


    @Override
    public User getNextStaff(@NotNull Integer appid) {
        Wrapper<Msg> msgWrapper = new EntityWrapper<>();
        msgWrapper.eq("appid",appid);
        msgWrapper.orderBy("create_time",false);
        Msg msg = msgServiceImpl.selectOne(msgWrapper);

        Wrapper<User> wrapper = new EntityWrapper<>();
        wrapper.like("appids",appid.toString());
        wrapper.eq("type",UserConstant.Type.USER.getCode());
        wrapper.ne("state", UserConstant.State.DELETE.getCode());
        wrapper.orderBy("id",true);
        //没有消息，直接取第一个客服
        if(Objects.isNull(msg)){
            return this.selectOne(wrapper);
        }
        //当前appid下最后一个为用户服务的客服的id
        Integer staffId;
        if(msg.getToId().equals(msg.getFromId())){
            staffId = msg.getFromId();
        }else{
            staffId = msg.getToId();
        }
        wrapper.gt("id",staffId);
        User user = this.selectOne(wrapper);
        //没有大于staffId，staffId为最后一个客服,返回第一个客服
        if(Objects.isNull(user)){
            wrapper = new EntityWrapper<>();
            wrapper.like("appids",appid.toString());
            wrapper.orderBy("id",true);
            return this.selectOne(wrapper);
        }
        return new User();
    }
}
